package com.util.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.CsvConfig;
import cn.hutool.core.text.csv.CsvParser;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvRow;
import com.util.excel.WriterH;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 合并两个有序文件
 */
@Slf4j
public class SortLine {

    int[] index;//根据那些列排序
    CsvParser csvParser1;
    CsvParser csvParser2;
    WriterH writerH;
    CsvRow row1;
    CsvRow row2;

    public SortLine(String path1, String path2, String res, int ...index) {
        this.index = index;
        CsvReadConfig csvConfig=new CsvReadConfig();
        csvConfig.setContainsHeader(true);
        csvParser1 = new CsvParser(FileUtil.getReader(path1, "UTF-8"), csvConfig);
        csvParser2 = new CsvParser(FileUtil.getReader(path2, "UTF-8"), csvConfig);
        writerH = new WriterH(res);
        row1 = csvParser1.next();
        writerH.write(csvParser1.getHeader());
    }

    public void invoke() {
        row2 = csvParser2.next();
        while (compare());
    }

    public boolean compare() {
        //结束
        if (row1 == null && row2 == null) {
            end();
            return false;
        }
        int i = 0;
        if (row1 == null) {
            i = 1;
        } else if (row2 == null) {
            i = -1;
        } else {
            for (int index1 : index) {
                i = row1.get(index1).compareTo(row2.get(index1));
                if(i!=0){
                    break;
                }
            }
        }
        //加入较小的，并获取下一个
        if (i > 0) {
            writerH.write(row2.getRawList());
            if (csvParser2.hasNext()) {
                row2 = csvParser2.next();
            } else {
                row2 = null;
            }
        } else {
            writerH.write(row1.getRawList());
            if (csvParser1.hasNext()) {
                row1 = csvParser1.next();
            } else {
                row1 = null;
            }
        }
        return true;
    }

    private void end() {
        try {
            csvParser2.close();
            csvParser1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writerH.close();
    }
}